var introEdit, uploader, iconurl='';
function checkTime(time) {
    if(time.search(/^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/) == -1)
        return false;
    else
        return true;
}
function formatTime(time) {
    var date = new Date(time);
    var month = (date.getMonth() + 1) < 10 ? '0'+(date.getMonth() + 1): (date.getMonth() + 1);
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return date.getFullYear() + '-' +  month + '-' + day;
}
var company = {
    getInitData: function() {
        $.ajax({
            url: window.domain + window.requestUrl.getCompanyUrl,
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.data == null) {
                    $('#uploader').show();
                    company.upload();
                    return;
                }
                if(res.status) {
                    var result = res.data.result;
                    if(result.iconUrl) {
                        $('.uploaded-wrap').show().find('img').prop('src', result.iconUrl);
                        iconurl = result.iconUrl;
                    }
                    $('[data-role="name"]').val(result.name);
                    $('[data-role="time"]').val(formatTime(result.foundTime));
                    $('[data-role="intro"]').val(result.intro);
                    introEdit.ready(function() {
                        introEdit.setContent(result.description, false);
                    })
                }
            },
            error: function(e) {
            }
        })

        $(document).on('click', '.delHadImg', function() {
            $('#uploader').show();
            $(this).closest('.uploaded-wrap').remove();
            company.upload();
            iconurl = '';
        })
    },
    ueditor: function() {
        introEdit = UE.getEditor('intro-edit', {scaleEnabled:true});
    },
    submit: function() {
        $('[data-role="submit"]').on('click', function() {
            if(iconurl == '' ) {
                iosOverlay({
                    text: '头像不能为空',
                    duration: 1000
                });
                return;
            }
            var name = $('[data-role="name"]').val();
            if(name == '' ) {
                iosOverlay({
                    text: '公司名称不能为空',
                    duration: 1000
                });
                return;
            }

            var time = $('[data-role="time"]').val();
            if(time == '' || !checkTime(time)) {
                iosOverlay({
                    text: '成立时间格式不正确',
                    duration: 1000
                });
                return;
            }

            var intro = $('[data-role="intro"]').val();
            if(intro == '' ) {
                iosOverlay({
                    text: '一句话简介不能为空',
                    duration: 1000
                });
                return;
            }

            var description = introEdit.getContent();
            if(description == '' ) {
                iosOverlay({
                    text: '公司简介不能为空',
                    duration: 1000
                });
                return;
            }

            $.ajax({
                url: window.domain + window.requestUrl.setCompanyUrl,
                type: 'post',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                data : {
                    name: name,
                    foundTime: time,
                    intro: intro,
                    description: description,
                    iconUrl: iconurl
                },
                success: function(res) {
                    if(typeof(res.not_login) != 'undefined') {
                        window.setCookie('go_back_link', window.location.href);
                        window.location.href = './login.html';
                        return;
                    }
                    if(res.status) {
                        iosOverlay({
                            text: '提交成功',
                            duration: 1000
                        });
                    } else {
                        iosOverlay({
                            text: res.msg,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        })
    },
    upload: function() {
        $(document).on('click', '.delPic', function() {
            $(this).closest('.file-item').remove();
            uploader.removeFile( $(this).attr('data-id') , true);
        })

        uploader = WebUploader.create({
            auto: true,
            method: 'POST',
            // swf文件路径
            swf: '/assets/webuploader/Uploader.swf',

            // 文件接收服务端。
            server: './config/ueditor?action=uploadimage',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#filePicker',
            duplicate: true,
            fileNumLimit: 1,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            },
            fileSingleSizeLimit: 1024*1024
        });

        uploader.on( 'fileQueued', function( file ) {
            var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                        '<img>' +
                        '<div class="delPic" data-id="'+file.id+'">删除</div>' +
                    '</div>'
                    ),
                $img = $li.find('img');

            $('#fileList').append( $li );

            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }

                $img.attr( 'src', src );
            }, 80, 80 );
        });

        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress span');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo( $li )
                        .find('span');
            }

            $percent.css( 'width', percentage * 100 + '%' );
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on( 'uploadSuccess', function( file , res) {

            $( '#'+file.id ).addClass('upload-state-done');
            iconurl = res.url;
        });

        // 文件上传失败，显示上传出错。
        uploader.on( 'uploadError', function( file ) {
            var $li = $( '#'+file.id ),
                $error = $li.find('div.error');

            // 避免重复创建
            if ( !$error.length ) {
                $error = $('<div class="error"></div>').appendTo( $li );
            }

            $error.text('上传失败');
        });

        // 完成上传完了，成功或者失败，先删除进度条。
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').remove();
        });

        uploader.on( 'error', function( type ) {
            if(type=="F_EXCEED_SIZE") {
                iosOverlay({
                    text: '文件大小不能超过1M',
                    duration: 1000
                });
            }
        });


    },
    init: function() {
        this.ueditor();
        this.getInitData();
        this.submit();
    }
}
company.init();
